﻿using System;
using BLL;
using DAL;
using Ext.Net;
using System.Data;

namespace ERP.Modules
{
    public partial class Barcode : System.Web.UI.UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                GetBarCode();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
            }
        }
        //Store
        protected void StoreBarCode_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetBarCode();
        }
        //Button
        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnCreateBarCode_Click(object sender, DirectEventArgs e)
        {
            /*-----------------
            -----Parram-------
            * txtData : Barcode
            * txtWidth : Chiều rộng hình
            * txtHeight : Chiều cao hình
            * txtBackColor : Màu nền hình Barcode
            * txtForeColor : Màu của 
            -----------------*/
            var strImageURL = "GenerateBarcodeImage.aspx?d=" + txtData.Text.Trim() + "&h=" + txtHeight.Text.Trim() + "&w=" +
                              txtWidth.Text.Trim() + "&bc=" + txtBackColor.Text.Trim() + "&fc=" + txtForeColor.Text.Trim() +
                              "&t=" + SelectcbEncodeType.SelectedItem.Value + "&il=" + chkGenerateLabel.Checked + "&if=" +
                              SelectImageFormat.SelectedItem.Value + "&align=" + GetAlignmentValue();
            BarcodeImage.ImageUrl = strImageURL;
            BarcodeImage.Width = Convert.ToInt32(txtWidth.Text);
            BarcodeImage.Height = Convert.ToInt32(txtHeight.Text);
            lbPath.Text = strImageURL;
        }
        protected void btnCancel_Click(object sender, DirectEventArgs e)
        {
            Wbarcode.Close();
        }
        protected void btnTutorial_Click(object sender, DirectEventArgs e)
        {

        }
        protected void btnForeColor_Click(object sender, DirectEventArgs e)
        {
            WColorFColor.Show();
        }
        protected void btnBackgroundColor_Click(object sender, DirectEventArgs e)
        {
            Wcolor.Show();
        }
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            ClearText();
            Wbarcode.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grBarCode.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    _flag = false;
                    GetBarCodeEdit(int.Parse(row.RecordID));
                    Wbarcode.Show();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grBarCode.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (var row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtBarCode { ID_BarCode = int.Parse(row.RecordID) };
                        BllBarCode.Delete(obj);
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetBarCode();
        }
        //Double-Click
        protected void BarCodeDblClick(object sender, DirectEventArgs e)
        {
            _flag = false;
            int ID_BarCode = int.Parse(e.ExtraParams["ID_BarCode"]);
            GetBarCodeEdit(ID_BarCode);
            Wbarcode.Show();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var _clsGetBarCode = new BllBarCode();
            var _dtSearch = _clsGetBarCode.GetBarCode(txtSearch.Text);
            if (_dtSearch != null && _dtSearch.Rows.Count > 0)
            {
                StoreBarCode.DataSource = _dtSearch;
                StoreBarCode.DataBind();
            }
            else
            {
                grBarCode.GetStore().RemoveAll();
            }
        }
        //Color-Picker
        protected void AjaxColor_Changed(object sender, DirectEventArgs e)
        {
            txtBackColor.Text = ColorPickerBg.Value;
            Wcolor.Close();
        }
        protected void ColorFcolor_Changed(object sender, DirectEventArgs e)
        {
            txtForeColor.Text = ColorFcolor.Value;
            WColorFColor.Close();
        }
        #endregion

        #region[Method]
        private void GetBarCode()
        {
            var _clsGetBarCode = new BllBarCode();
            var _dtGetBarCode = _clsGetBarCode.GetBarCode(txtSearch.Text);
            if (_dtGetBarCode != null && _dtGetBarCode.Rows.Count > 0)
            {
                StoreBarCode.DataSource = _dtGetBarCode;
                StoreBarCode.DataBind();
            }
            else
            {
                grBarCode.GetStore().RemoveAll();
            }
        }
        private void GetBarCodeEdit(int id)
        {
            var _clsGetBarCodeEdit = new BllBarCode();
            var _dtGetBarCodeEdit = _clsGetBarCodeEdit.GetBarCodeEdit(id);
            if (_dtGetBarCodeEdit != null && _dtGetBarCodeEdit.Rows.Count > 0)
            {
                lbID.Text = _dtGetBarCodeEdit.Rows[0]["ID_BarCode"].ToString();
                txtData.Text = _dtGetBarCodeEdit.Rows[0]["BarCode"].ToString();
                txtBackColor.Text = _dtGetBarCodeEdit.Rows[0]["Backcolor"].ToString();
                txtForeColor.Text = _dtGetBarCodeEdit.Rows[0]["Forecolor"].ToString();
                txtWidth.Text = _dtGetBarCodeEdit.Rows[0]["Width"].ToString();
                txtHeight.Text = _dtGetBarCodeEdit.Rows[0]["Height"].ToString();
                SelectcbEncodeType.SetValue(_dtGetBarCodeEdit.Rows[0]["EncodeType"].ToString());
                SelectImageFormat.SetValue(_dtGetBarCodeEdit.Rows[0]["ImageFormat"].ToString());
                BarcodeImage.ImageUrl = _dtGetBarCodeEdit.Rows[0]["ImagesPath"].ToString();
                lbPath.Text = _dtGetBarCodeEdit.Rows[0]["ImagesPath"].ToString();
                if ((bool)_dtGetBarCodeEdit.Rows[0]["GenerateLabel"])
                {
                    chkGenerateLabel.Checked = true;
                }
                else
                {
                    chkGenerateLabel.Checked = false;
                }
                if (_dtGetBarCodeEdit.Rows[0]["Alignment"].ToString() == "c")
                    rbAlignCenter.Checked = true;
                if (_dtGetBarCodeEdit.Rows[0]["Alignment"].ToString() == "l")
                    rbAlignLeft.Checked = true;
                if (_dtGetBarCodeEdit.Rows[0]["Alignment"].ToString() == "r")
                    rbAlignRight.Checked = true;
            }
        }
        private string GetAlignmentValue()
        {
            if (rbAlignCenter.Checked)
                return "c";
            if (rbAlignLeft.Checked)
                return "l";
            if (rbAlignRight.Checked)
                return "r";
            return "c";
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsGetBarCodeCheck = new BllBarCode();
            var dtCheck = _clsGetBarCodeCheck.GetBarCode(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (lbID.Text != dr["ID_BarCode"].ToString())
                    {
                        if (txtData.Text == dr["BarCode"].ToString() && SelectcbEncodeType.SelectedItem.Value == dr["EncodeType"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã vạch " + txtData.Text + " này đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (_flag)
            {
                InsertValue();
            }
            else
            {
                UpdateValue();
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var strImageURL = "../Modules/GenerateBarcodeImage.aspx?d=" + txtData.Text.Trim() + "&h=" + txtHeight.Text.Trim() + "&w=" +
                              txtWidth.Text.Trim() + "&bc=" + txtBackColor.Text.Trim() + "&fc=" + txtForeColor.Text.Trim() +
                              "&t=" + SelectcbEncodeType.SelectedItem.Value + "&il=" + chkGenerateLabel.Checked + "&if=" +
                              SelectImageFormat.SelectedItem.Value + "&align=" + GetAlignmentValue();
                    var obj = new EtBarCode
                    {
                        EncodeType = SelectcbEncodeType.SelectedItem.Value,
                        BarCode = txtData.Text,
                        GenerateLabel = chkGenerateLabel.Checked,
                        ImageFormat = SelectImageFormat.SelectedItem.Value,
                        ImagesPath = strImageURL,
                        Width = txtWidth.Text,
                        Height = txtHeight.Text,
                        Alignment = GetAlignmentValue(),
                        Backcolor = txtBackColor.Text,
                        Forecolor = txtForeColor.Text
                    };
                    BllBarCode.Insert(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mã vạch thành công !");
                    GetBarCode();
                    ClearText();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtBarCode
                    {
                        ID_BarCode = int.Parse(lbID.Text),
                        EncodeType = SelectcbEncodeType.SelectedItem.Value,
                        BarCode = txtData.Text,
                        GenerateLabel = chkGenerateLabel.Checked,
                        ImageFormat = SelectImageFormat.SelectedItem.Value,
                        ImagesPath = lbPath.Text,
                        Width = txtWidth.Text,
                        Height = txtHeight.Text,
                        Alignment = GetAlignmentValue(),
                        Backcolor = txtBackColor.Text,
                        Forecolor = txtForeColor.Text
                    };
                    BllBarCode.Update(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật mã vạch thành công !");
                    GetBarCode();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }
        #endregion

        #region[ClearText]
        private void ClearText()
        {
            txtData.Text = "038000356217";
            txtForeColor.Text = "000000";
            txtBackColor.Text = "FFFFFF";
            txtWidth.Text = "150";
            txtHeight.Text = "50";
            chkGenerateLabel.Checked = true;
            BarcodeImage.ImageUrl = string.Empty;
            SelectImageFormat.Text = string.Empty;
            SelectcbEncodeType.Text = string.Empty;
        }
        #endregion
    }
}